<script setup>
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import useFormEvent from '@/core/hooks/useFormEvent'
import attributeApi from '@/api/goods/AttributeApi'
import categoryApi from '@/api/goods/CategoryApi'

const formRef = ref() // 表单ID
const state = reactive({
  visible: false,
  loading: false, // 加载开关
  parentOptions: [],
  // 
  tagInputVisible: {},
  tagInputValue: {},
  // 
  optInputVisible: false,
  optInputValue: '',
})
// 表单结构
const original = {
  id: '',
  name: '',
  catalogId: 0,
  catalogName: '',
  idx: 0,
  notes: '',
  options: []
}
// 表单数据
const formState = reactive({})
// 表单 处理
const {
  onCancel, InitializeData, refreshData
} = useFormEvent({ state: state, remoteApi: attributeApi, formState: formState, original: original, formRef: formRef })
// 完成 保存数据
const onFinish = (values) => {
 
  if(!Array.isArray(values.options)){
    message.warning('请添加属性')
    return
  }
  
  // 检查每项属性
  for(let key in values.options) {
    if(values.options[key].data.length ==0){
      message.warning(`${values.options[key].name} 属性的选项值`)
      return
    }
  }
  //****************************************** */
  state.loading = true
  attributeApi.saveData(values).then(res => {
    refreshData()
    message.success(res.msg)
    state.visible = false
  })
    .finally(() => {
      state.loading = false
      formRef.value.clearValidate()
    })
}
// 重写初始化
const initializationData = primaryKey=>{
  state.optInputVisible = false
  InitializeData(primaryKey)
}
//向父组件暴露方法和属性
defineExpose({ InitializeData: initializationData})

/********************************* */
const onShowOptionInput = () => {
  state.optInputVisible = true
  state.optInputValue =''
}

const handleOptionInputConfirm=()=>{
  if(state.optInputValue ==''){
    message.error('请输入属名')
    return
  }
  if(formState.options.some(it=> it.name==state.optInputValue)) {
    message.error('该属名已存在了')
    return
  }
  let item = {name: state.optInputValue, data: []}
  formState.options.push(item) 
  state.optInputVisible = false
}
//移去整个属性
const onRemoveOption=(item)=>{
  //delete formState.options[key]
  formState.options = formState.options.filter(it=> it.name != item.name )
}
//
// 属性值什处理
const onCloseTag =(tag, item)=>{
  item.data = item.data.filter(it=> it != tag)
}
const onShowTagInput = (item) => {
  state.tagInputVisible[item.name] = true
  state.tagInputValue[item.name] = ''
}
const handleTagInputConfirm = (item) => {
  const inputValue = state.tagInputValue[item.name]
  let tags = item.data
  if (inputValue && tags.indexOf(inputValue) === -1) {
    item.data = [...tags, inputValue]
  }
  delete state.tagInputValue[item.name]
  delete state.tagInputVisible[item.name]
}
// 加载页时初始化选项等基础数据
onMounted(() => {
  categoryApi.getTreeOptions().then(res => {
    state.parentOptions.push(res.data)
  })
})
</script>
<template>
  <a-drawer
    v-model:visible="state.visible"
    :title="`属性信息`"
    placement="right"
    :width="'50%'"
  >
    <a-card hoverable>
      <a-spin :spinning="state.loading">
        <!-- 表单内容 begin -->
        <a-form
          ref="formRef"
          :model="formState"
          :label-col="{ span:4 }"
          :wrapper-col="{ span: 10}"
          :scroll-to-first-error="true"
          :validate-on-rule-change="false"
          @finish="onFinish"
        >
          <a-row>
            <a-col :span="24">
              <a-form-item
                label="所属分类" name="catalogId" :label-col="{span:4}"
                :rules="[{ required: true, message: '请选择所属分类' }]">
                <a-tree-select
                  v-model:value="formState.catalogId"
                  placeholder="选择分类" show-search allow-clear
                  tree-default-expand-all
                  :tree-data="state.parentOptions" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="模板名称" name="name" :label-col="{span:4}"
                :rules="[{ required: true, message: '请输入名称!' }]">
                <a-input v-model:value="formState.name" show-count :minlength="2" :maxlength="20" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="排序" name="idx" :label-col="{span:4}"
                :rules="[{ required: true, message: '请输入排序!' }]">
                <a-input-number v-model:value="formState.idx" placeholder="排序" :min="0" :max="10" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="备注" name="notes" :label-col="{span:4}" :wrapper-col="{ span: 21}">
                <a-textarea v-model:value="formState.notes" show-count />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="属性项" name="options" :label-col="{span:4}" :wrapper-col="{ span: 21}" :rules="[{ required: true, message: '请输入排序!' }]">
                <div v-for="(item, key) in formState.options" :key="key" class="option-box">
                  <div class="box-title">
                    <span class="title">{{ item.name }}</span>
                    <span class="btn">
                      <a-button type="link" @click="onRemoveOption(item)"><close-outlined /></a-button>
                    </span>
                  </div>
                  <div class="box-body">
                    <a-tag v-for="(tag, index) in item.data" :key="index" :closable="true" @close="onCloseTag(tag, item)">
                      {{ tag }}
                    </a-tag>
                    <a-input
                      v-if="state.tagInputVisible[item.name]"
                      v-model:value="state.tagInputValue[item.name]"
                      type="text" size="small"
                      :style="{ width: '78px' }"
                      @blur="handleTagInputConfirm(item)"
                      @keyup.enter="handleTagInputConfirm(item)"
                    />
                    <a-tag v-else style="background: #fff; border-style: dashed" @click="onShowTagInput(item)">
                      <plus-outlined />
                    </a-tag>
                  </div>
                </div>
                <div class="option-action">
                  <a-button v-if="state.optInputVisible== false" type="info" @click="onShowOptionInput"><plus-outlined />增加属性</a-button>
                  <div v-if="state.optInputVisible== true">
                    <a-input v-model:value="state.optInputValue" style="width: 130px;" />
                    <a-button type="primary" size="small" @click="handleOptionInputConfirm">确定</a-button>
                    <a-button size="small" @click="state.optInputVisible = false">取消</a-button>
                  </div>
                </div>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item name="id">
                <a-space wrap>
                  <a-button type="primary" html-type="submit" size="large" block :loading="state.loading">保存</a-button>
                  <a-button size="large" block @click="onCancel">取消</a-button>
                </a-space>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-card>
  </a-drawer>
</template>
<style lang="less" scoped>
.option-box{ 
  border: 1px solid #f0f0f0;
  margin-bottom: 10px;
  padding: 5px 8px;
  .box-title {
    display: flex;
    justify-content:space-between;
    align-items:center;
    border-bottom: 1px solid #f0f0f0;
    .title {
      font-weight: 600; text-shadow: 2px 2px 4px #e9e7e7; 
    }
  }
  .box-body {
    padding: 5px 12px;
  }
  
}
.option-action {
  padding: 2px 5px;
}
</style>